<?php

namespace common\models\datas;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%integral_record}}".
 *
 * @property integer $id
 * @property integer $customer_id
 * @property integer $integral
 * @property integer $created_at
 * @property integer $user_id
 */
class IntegralRecord extends \common\components\bases\BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%integral_record}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'customer_id'], 'required'],
            [['content'], 'string'],
            [['id', 'customer_id', 'site_id','integral', 'created_at', 'user_id','task_id'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', 'ID'),
            'customer_id' => Yii::t('common', '会员编号'),
            'integral' => Yii::t('common', '金额'),
            'site_id' => Yii::t('common', '分店id'),
            'content' => Yii::t('common', '描述'),
            'created_at' => Yii::t('common', 'Created At'),
            'user_id' => Yii::t('common', 'User ID'),
            'task_id' => Yii::t('common', 'task id'),
        ];
    }


    public function fields()
    {
        $fields = parent::fields();
        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        return $fields;
    }

    public function extraFields()
    {
        return [
            'customer_name' => function () {
                return isset($this->customer) ? $this->customer->name : '';
            },
            'admin_name' => function () {
                return isset($this->admin) ? $this->admin->username : '';
            },
        ];
    }

    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
    }

    public function getAdmin()
    {
        return $this->hasOne(Admin::className(), ['id' => 'user_id']);
    }

    public function getIntegral()
    {
        return $this->hasOne(IntegralConfigItem::className(), ['id' => 'intergral_id']);
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],

                ],
            ],

        ]);
    }
}
